package com.daxidi.cn.utils;


import org.apache.commons.lang3.StringUtils;

import java.io.*;

public class FileContextReplace {

    public static String htmlString(String filePath) throws UnsupportedEncodingException {
        String str = "";
        File file = new File(filePath);
        try {
            FileInputStream in = new FileInputStream(file);
            // size 为字串的长度 ，这里一次性读完
            int size = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            str = new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = StringUtils.substringAfter(str, "<body>\n");
        String s2 = StringUtils.substringBeforeLast(s, "\n</body>");
        if (s2.lastIndexOf("</body>") != -1) {
            s2 = StringUtils.substringBeforeLast(s, "</body>");
        }
        str = s2;
        return str;
    }

    public static void autoReplace(String filePath, String newStr) {
        String contentHead = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>泗洪工会</title>\n" +
                "</head>\n" +
                "<body>\n";
        String contentFoot = "\n</body>\n" +
                "</html>";
        // 文件新内容
        newStr = contentHead + newStr + contentFoot;

        // 读取文件 获取原来文件内容 并转成字节数组
        File file = new File(filePath);
        Long fileLength = file.length();
        byte[] fileContext = new byte[fileLength.intValue()];
        FileInputStream in = null;
        PrintWriter out = null;
        try {
            in = new FileInputStream(filePath);
            in.read(fileContext);
            // 文件原来的内容          避免出现中文乱码
            String oldStr = new String(fileContext, "UTF-8");
            // 替换文件内容
            oldStr = oldStr.replace(oldStr, newStr);
            out = new PrintWriter(filePath);
            out.write(oldStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
